package com.socialcoco.exception;

import com.socialcoco.respone.BaseResponse;
import com.socialcoco.respone.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class globalException {
    @ExceptionHandler(value = AuthorizationException.class)
    public Map<String, String> handleException(AuthorizationException e) {
        Map<String, String> result = new HashMap<>();
        result.put("status","400");
        String message=e.getMessage();
        String msg=message.substring(message.indexOf("[")+1,message.indexOf("]"));
        if (message.contains("role")) {
            result.put("msg", "对不起，您没有" + msg + "角色");
        } else if (message.contains("permission")) {
            result.put("msg", "对不起，您没有" + msg + "权限");
        } else {
            result.put("msg", "对不起，您的权限有误");
        }
        return result;
    }
//    @ExceptionHandler(value = IndexOutOfBoundsException.class)
//    public BaseResponse<Object> handleNullException(IndexOutOfBoundsException e) {
//        Map<String, String> result = new HashMap<>();
//        result.put("status","400");
//        result.put("msg","账号或密码错误");
//        return ResultUtils.error(400,"账号或密码错误");
//    }
//    @ExceptionHandler(value = NullPointerException.class)
//    public BaseResponse<Object> NullException(NullPointerException e) {
//        log.error(e.getMessage());
//        return ResultUtils.error(4004,"空指针异常！");
//    }
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public BaseResponse<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        return ResultUtils.error(4000,"参数校验异常！");
    }
}
